package com.szgd.service.schedule;

import com.szgd.dao.ecdata.schedule.TunnellingWorkScheduleMapper;
import com.szgd.service.personnel.AttachService;
import com.szgd.service.project.BidService;
import com.szgd.service.project.SiteService;
import com.szgd.service.sys.SimulateBaseService;
import com.szgd.util.ExcelUtil;
import com.szgd.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class TunnellingWorkScheduleService extends SimulateBaseService {

    @Autowired
    TunnellingWorkScheduleMapper tunnellingWorkScheduleMapper;
    @Autowired
    SiteService siteService;
    @Autowired
    BidService bidService;
    @Autowired
    AttachService attachService;
    @Autowired
    FileUtil fileUtil;

    public List<Map<String,Object>> getTunnellingWorkScheduleList(Map<String, Object> params)
    {
        return  tunnellingWorkScheduleMapper.getTunnellingWorkScheduleList(params);
    }

    public void insertTunnellingWorkSchedule(Map<String, Object> params)
    {
        tunnellingWorkScheduleMapper.insertTunnellingWorkSchedule(params);
    }

    public boolean importTunnellingWorkSchedule(MultipartFile[] improtFiles,String loginId) throws IOException, ParseException {
        String failedFilename = null;
        String susscessFilename = null;
        for (MultipartFile file : improtFiles) {//循环

            String fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
            InputStream is = file.getInputStream();
            if (suffix.equalsIgnoreCase("xls")|| suffix.equalsIgnoreCase("xlsx") )//excel文件
            {
                List<Map<String, Object>> tunnellingResultList = ExcelUtil.readFromTunnellingWorkScheduleExcel(fileName,is);
                int beginindex = fileName.indexOf("（");
                if (beginindex == -1)
                    beginindex = fileName.indexOf("(");
                int endindex = fileName.indexOf("）");
                if (endindex == -1)
                    endindex = fileName.indexOf(")");
                String dateStr  = "";
                if (beginindex > 0 && endindex > beginindex)
                    dateStr  = fileName.substring(beginindex+1,endindex).replace(".","-");
                else
                {
                    /*SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    dateStr = formatter.format(new Date());*/
                    return  false;
                }
                //log.info("#############关键信息################---mbResultList :"+ JSON.toJSONString());
                Map<String, Object> attachMap = null;
                if(tunnellingResultList != null && tunnellingResultList.size() > 0)//有数据，保存excel文件
                {
                    try {
                        is = file.getInputStream();
                        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
                        String date = df.format(new Date());
                        String newFileName = fileUtil.uploadFile(is,fileName,date);

                        Map<String, Object> paramMap = new HashMap<String, Object>();
                        paramMap.put("creator",loginId);
                        paramMap.put("uploader",loginId);
                        paramMap.put("name",newFileName);
                        paramMap.put("type","ATTACH_DOC");
                        paramMap.put("source","ATTACH_TUNNELLING_SCHEDULE");
                        attachMap = attachService.saveAttach(paramMap);
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
                boolean sussb = tunnellingResultToTable(tunnellingResultList,suffix,dateStr,attachMap,loginId);
                if (!sussb && attachMap != null)
                {
                    attachService.deleteAttach(attachMap);
                }

                return sussb;
            }
        }
        return false;
    }

    public boolean tunnellingResultToTable(List<Map<String, Object>> tunnellingResultList,String suffix,String dateStr,Map<String, Object> attachMap,String loginId) {
        if (tunnellingResultList == null || tunnellingResultList.size() == 0)
            return false;


        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("statisticsTime",dateStr);

        List<Map<String,Object>> tempList = getTunnellingWorkScheduleList(paramMap);
        if (tempList != null && tempList.size() > 0)
        {
            String attachId = tempList.get(0).get("attachId")==null?null:tempList.get(0).get("attachId").toString();
            if (attachId != null)
            {
                paramMap.put("id",attachId);
                attachService.deleteAttach(paramMap);
            }
            tunnellingWorkScheduleMapper.deleteTunnellingWorkSchedule(paramMap);
        }


        for (int i = 0; i < tunnellingResultList.size(); i++) {
            Map<String, Object> tunnellingResultMap = tunnellingResultList.get(i);

            Map<String, Object> siteMap = siteService.getSiteByName(tunnellingResultMap.get("beginSiteName")==null?"":tunnellingResultMap.get("beginSiteName").toString());
            if (siteMap == null)
                tunnellingResultMap.put("beginSiteId",null);
            else
                tunnellingResultMap.put("beginSiteId",siteMap.get("id"));

            Map<String, Object> bidMap = bidService.getBidByName(tunnellingResultMap.get("bidName")==null?"":tunnellingResultMap.get("bidName").toString());
            if (bidMap == null)
                tunnellingResultMap.put("bidId",null);
            else
                tunnellingResultMap.put("bidId",bidMap.get("id"));

            String  cumulativeComplete = tunnellingResultMap.get("cumulativeComplete")==null?"":tunnellingResultMap.get("cumulativeComplete").toString();
            String  intervalLength = tunnellingResultMap.get("intervalLength")==null?"":tunnellingResultMap.get("intervalLength").toString();
            String  completeRate = tunnellingResultMap.get("completeRate")==null?"":tunnellingResultMap.get("completeRate").toString();
            if (completeRate.length()==0 && cumulativeComplete.length() > 0 && intervalLength.length() > 0)
            {
                DecimalFormat df = new DecimalFormat("0.00");//格式化小数
                completeRate = df.format((float)(Float.parseFloat(cumulativeComplete)*100)/Float.parseFloat(intervalLength));//返回的是String类型
                tunnellingResultMap.put("completeRate",completeRate);
            }

            tunnellingResultMap.put("attachId",attachMap.get("id"));
            tunnellingResultMap.put("statisticsTime",dateStr);
            tunnellingResultMap.put("creator",loginId);
            tunnellingWorkScheduleMapper.insertTunnellingWorkSchedule(tunnellingResultMap);
        }
        return true;
    }

    public List<String> getBidIds(Map<String, Object> params){
        List<String> bidIds = new ArrayList<>();
        Object idObject = params.get("bidId");
        if (idObject != null) {
            if (idObject instanceof String || idObject instanceof Integer) {
                bidIds.add(idObject.toString());
            } else if (idObject instanceof ArrayList) {
                bidIds = (ArrayList<String>) idObject;
            }
        }
        return bidIds;
    }

    public Map<String,Object> getChart(Map<String, Object> params)
    {
        List<String> bidIds = this.getBidIds(params);
        params.put("bidIds",bidIds);
        Map<String,Object> res = new HashMap<>();
        List<String> legend = new ArrayList<>();
        legend.add("本周完成");
        legend.add("累计完成");
        legend.add("区间长度");
        legend.add("隧道施工进度");
        List<List<Double>> series = new ArrayList<>();
        String bidId = params.get("bidId")==null?"":params.get("bidId").toString().replace("null","");
        if(bidId.length() == 0){
            params.put("bidId",null);
        }
        List<Map<String,Object>> mapList = tunnellingWorkScheduleMapper.getChart(params);
        List<String> xAxis = new ArrayList<>();
        List<Double> ratetemp = new ArrayList<>();
        List<Double> curtemp = new ArrayList<>();
        List<Double> cumtemp = new ArrayList<>();
        List<Double> tottemp = new ArrayList<>();
        for(int i = 0; i < mapList.size(); i++){
            String isSum = mapList.get(i).get("isSum").toString();
            if(isSum.equalsIgnoreCase("1")){
                continue;
            }
            xAxis.add(mapList.get(i).get("intervalName").toString());
            ratetemp.add(Double.valueOf(mapList.get(i).get("completeRate").toString()));
            curtemp.add(Double.valueOf(mapList.get(i).get("currentComplete").toString()));
            cumtemp.add(Double.valueOf(mapList.get(i).get("cumulativeComplete").toString()));
            tottemp.add(Double.valueOf(mapList.get(i).get("intervalLength").toString()));
        }
        series.add(curtemp);
        series.add(cumtemp);
        series.add(tottemp);
        series.add(ratetemp);

        res.put("legend",legend);
        res.put("xAxis",xAxis);
        res.put("series",series);
        return res;
    }

    public List<List<Map<String,Object>>> getChartTable(Map<String, Object> params)
    {
        List<String> bidIds = this.getBidIds(params);
        params.put("bidIds",bidIds);
        List<List<Map<String,Object>>> res = new ArrayList<>();
        List<Map<String,Object>> chartList = tunnellingWorkScheduleMapper.getChart(params);
        String bidName = chartList.get(0).get("bidName")==null?"":chartList.get(0).get("bidName").toString();
        List<Map<String,Object>> temp = new ArrayList<>();
        for(int i = 0; i < chartList.size(); i++){
            String bidTemp = chartList.get(i).get("bidName")==null?"":chartList.get(i).get("bidName").toString();
            if(bidTemp.equalsIgnoreCase(bidName)){
                temp.add(chartList.get(i));
                bidName = bidTemp;
            }else{
                res.add(temp);
                temp = new ArrayList<>();
                temp.add(chartList.get(i));
                bidName = bidTemp;
            }
        }
        res.add(temp);
        return res;
    }

    public List<Map<String,Object>> getTime(Map<String, Object> params){
        return tunnellingWorkScheduleMapper.getTime(params);
    }

    public List<Map<String,Object>> getHistoryAttach(Map<String, Object> params){
        return tunnellingWorkScheduleMapper.getHistoryAttach(params);
    }

    public Double tunnellingCompleteRateAvg(Map<String, Object> params){
        Double d = tunnellingWorkScheduleMapper.tunnellingCompleteRateAvg(params);
        if (d==null)
            d = 0.0;
        return d;

    }
}
